package com.atguigu.tingshu.album.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author 胡hu
 */
@Component
@Slf4j
public class TrackReciever {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TrackInfoService trackInfoService;
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = MqConst.QUEUE_TRACK_STAT_UPDATE, durable = "true", autoDelete = "false"),
                    exchange = @Exchange(value = MqConst.EXCHANGE_TRACK),
                    key = {MqConst.ROUTING_TRACK_STAT_UPDATE}
            )
    )
    public void saveTrackStat(String msg, Message message, Channel channel) throws IOException {
        try {
            if (!ObjectUtils.isEmpty(msg)){
                TrackStatMqVo trackStatMqVo = JSON.parseObject(msg, TrackStatMqVo.class);
                log.info("收到消息了：{}", trackStatMqVo);
                //获取交易编号
                String businessNo = trackStatMqVo.getBusinessNo();
                Boolean ifAbsent = this.redisTemplate.opsForValue().setIfAbsent(businessNo, "1", 24, TimeUnit.HOURS);
                if (ifAbsent){
                    try {
                        trackInfoService.updateTrackStat(trackStatMqVo);
                    } catch (Exception e) {
                        //异常，删除上一个key
                        this.redisTemplate.delete(businessNo);
                        log.error(e.getMessage(), e);
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(),e);
        }
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }
}
